import axios from 'axios'
import router from '@/router'
import Cookies from 'js-cookie'
import {
  Message
} from 'iview'

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      if (Cookies.get('token')) {
        config.headers.token = Cookies.get('token')
        config.headers.appId = '03e35b82-9985-44b6-8d44-44a1c4fb9609'
      }
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const {
        data,
        status
      } = res
      return {
        data,
        status
      }
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const {
          request: {
            statusText,
            status
          },
          config
        } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: {
            responseURL: config.url
          }
        }
      }
      Message.error((error.response && error.response.data && error.response.data.message) || (error.response && error.response.data && error.response.data.error) || (error.message))
      if (error.response && error.response.status === 500) {
        router.push({
          name: 'error_500'
        })
      }
      if (error.response && error.response.status === 401) {
        router.push({
          name: 'error_401'
        })
      }
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    // const instance = axios.create({
    //   responseType: 'blob'
    // })
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
